/**
 * Copyright (c) 2013-3-14 by droidsde
 * <p>
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject
 * to the following conditions:
 * <p>
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 * <p>
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT
 * WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR
 * PURPOSE AND NONINFRINGEMENT. IN NO EVENT
 * SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR
 * IN CONNECTION WITH THE SOFTWARE OR
 * THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 * @Title: UIHelper.java
 * @version
 */
package com.ssyc.common.utils;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.ListView;
import android.widget.Toast;

import com.ssyc.common.R;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipInputStream;

/**
 * @author xjin
 */
public class UIHelper {

    public static List<Activity> main_activities = new ArrayList<Activity>();

    public static List<Activity> cart_activities = new ArrayList<Activity>();

    public static List<Activity> change_community_activities = new ArrayList<Activity>();

    public static List<Activity> orders_activities = new ArrayList<Activity>();

    public static List<Activity> code_activities = new ArrayList<Activity>();

    public static boolean ISSHOWLOG = false;

    public static List<Activity> activities = new ArrayList<Activity>();

    public static void exitApp() {
        for (int i = 0; i < activities.size(); i++) {
            Activity activity = activities.get(i);
            if (null != activity) {
                activity.finish();
            }
        }
    }

    public static String getImei(Context context, String imei) {
        try {
            TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            imei = telephonyManager.getDeviceId();
        } catch (Exception e) {
            Log.e(UIHelper.class.getSimpleName(), e.getMessage());
        }
        return imei;
    }


    public static boolean isEmpty(String s) {
        if (null == s)
            return true;
        if (s.length() == 0)
            return true;
        if (s.trim().length() == 0)
            return true;
        return false;
    }

    /**
     * 获取客户端版本号
     *
     * @return
     */
    public static String getVersionName(Context context) {
        try {
            final PackageInfo packageInfo = context.getPackageManager()
                    .getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionName;
        } catch (final NameNotFoundException e) {
            // Application not installed.
        }
        return "";
    }

    /**
     * 获取客户端版本号
     *
     * @return
     */
    public static String getVersionCode(Context context) {
        try {
            final PackageInfo packageInfo = context.getPackageManager()
                    .getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionCode + "";
        } catch (final NameNotFoundException e) {
            // Application not installed.
        }
        return "";
    }


    private static Dialog mProgressDialog;

    public static synchronized void showDialog(Context context, int resId) {
        final LoadingDialog dialog = new LoadingDialog(context,
                R.style.CustomProgressDialog);
        //设置点击空白处不消失
        dialog.setCanceledOnTouchOutside(false);
        dialog.setMsg(resId);
        mProgressDialog = dialog;
        mProgressDialog.show();
    }

    public static synchronized void showDialog(Context context, String message) {
        final LoadingDialog dialog = new LoadingDialog(context,
                R.style.CustomProgressDialog);
        //设置点击空白处不消失
        dialog.setCanceledOnTouchOutside(false);
        dialog.setMsg(message);
        dialog.setCancelable(true);
        mProgressDialog = dialog;
        if (mProgressDialog != null)
            mProgressDialog.show();
    }


    public static synchronized void showDialog(Context context, String message, DialogInterface.OnDismissListener listener) {
        final LoadingDialog dialog = new LoadingDialog(context,
                R.style.CustomProgressDialog);
        dialog.setMsg(message);
        dialog.setOnDismissListener(listener);
        dialog.setCancelable(true);
        mProgressDialog = dialog;
        if (mProgressDialog != null)
            mProgressDialog.show();
    }

    public static synchronized void showDialog(Context context) {
        try {
            final LoadingDialog dialog = new LoadingDialog(context,
                    R.style.CustomProgressDialog);
            dialog.setMsg(R.string.com_loading);
            mProgressDialog = dialog;
            mProgressDialog.show();
        } catch (Exception e) {

        }
    }

    public static synchronized void dismissDialog() {
        if (null != mProgressDialog && mProgressDialog.isShowing()) {
            try {
                mProgressDialog.dismiss();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            }

        }
    }

    public static void showToast(Context context, int resId) {
        String text = context.getString(resId);
        showToast(context, text);
    }

    public static void showToast(Context context, String text) {
        Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
    }

    /**
     * 以最省内存的方式读取本地资源的图片
     *
     * @return
     * @paramresId
     */
    public static Bitmap readBitMap(Context context, int resId) {
        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inPreferredConfig = Bitmap.Config.RGB_565;
        opt.inPurgeable = true;
        opt.inInputShareable = true;
        // 获取资源图片
        InputStream is = context.getResources().openRawResource(resId);
        return BitmapFactory.decodeStream(is, null, opt);
    }

    /**
     * 格式价格，去掉后面的0
     *
     * @param price
     * @return
     */
    public static String formatPrice(double price) {
        if (Math.round(price) - price == 0) {
            return String.valueOf((long) price);
        }
        return String.valueOf(price);
    }


    /**
     * 根据宽度进行图片缩放
     *
     * @param bitmap 原始图片
     * @param width  新图片宽度
     * @return 新图片
     */
    public static Bitmap onImageZoomToWidth(Bitmap bitmap, int width) {
        int widthBitmap = bitmap.getWidth();
        int heightBitmap = bitmap.getHeight();
        int height = width * heightBitmap / widthBitmap;
        // 计算缩放比例
        float scaleWidth = ((float) width) / widthBitmap;
        float scaleHeight = ((float) height) / heightBitmap;
        // 取得想要缩放的matrix参数
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        return Bitmap.createBitmap(bitmap, 0, 0, widthBitmap, heightBitmap,
                matrix, true);
    }

    static Map<String, String> map = new HashMap<String, String>();

    static {
        map.put("-1", "访问服务器超时");
        map.put("0", "网络不通，请检查您的网络设置");
        map.put("404", "客户端数据错误");
        map.put("500", "服务器开小差了，请稍后再试");
    }

    public static String paserError(String errorNo,
                                    Map<String, String>... customMap) {
        if (TextUtils.isEmpty(errorNo)) {
            return "服务器忙，请稍后再试";
        }
        Map<String, String> temp_map = new HashMap<String, String>();
        temp_map.putAll(map);
        if (null != customMap) {
            for (int i = 0; i < customMap.length; i++) {
                temp_map.putAll(customMap[i]);
            }
        }
        String errorMessage = temp_map.get(errorNo);
        return TextUtils.isEmpty(errorMessage) ? "服务器忙，请稍后再试" : errorMessage;
    }

    public static boolean extraZip(Context context, String appid, String temp) {
        boolean isExtraSucceed = false;
        String dir = context.getDir("qinlife", Context.MODE_PRIVATE)
                .getAbsolutePath();
        String path = dir + File.separator + appid;
        File installFolder = new File(path);
        if (installFolder.exists()) {
            installFolder.delete();
        }
        installFolder.mkdir();
        try {
            int leng = 0;
            byte[] buf = new byte[1024];

            FileInputStream fins = new FileInputStream(temp);
            ZipInputStream zis = new ZipInputStream(fins);

            for (ZipEntry entry = zis.getNextEntry(); entry != null; entry = zis
                    .getNextEntry()) {
                String enName = entry.getName();
                if (entry.isDirectory()) {
                    enName = enName.substring(0, enName.length() - 1);
                    File folder = new File(path + File.separator + enName);
                    folder.mkdirs();
                } else {
                    File file = new File(path + File.separator + enName);
                    file.createNewFile();
                    FileOutputStream fos = new FileOutputStream(file);
                    while ((leng = zis.read(buf)) != -1) {
                        fos.write(buf, 0, leng);
                    }
                    fos.flush();
                    fos.close();
                }
            }
            zis.close();
            fins.close();
            isExtraSucceed = true;
        } catch (ZipException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return isExtraSucceed;
    }

    /**
     * @author chenyuan log日志显示的工具类
     * @since201506.4
     */
    public static void showLog(String tag, String msg) {
        if (ISSHOWLOG) {
        }
    }

    public static String doubuleTOSTR(Double d) {
        DecimalFormat format = new DecimalFormat("#0.00");
        String sMoney = format.format(d);
        return sMoney;
    }

    public static void setListViewHeight(ListView listView) {
        try {
            int totalHeight = 0;

		/* 得到适配器 */

            Adapter adapter = listView.getAdapter();

		/* 遍历控件 */

            for (int i = 0; i < adapter.getCount(); i++) {

                View view = adapter.getView(i, null, listView);

			/* 测量一下子控件的高度 */

                view.measure(View.MeasureSpec.UNSPECIFIED,
                        View.MeasureSpec.UNSPECIFIED);

                totalHeight += view.getMeasuredHeight();

            }

		/* 控件之间的间隙 */

            totalHeight += listView.getDividerHeight() * (listView.getCount() - 1);

		/* 2、赋值给ListView的LayoutParams对象 */

            ViewGroup.LayoutParams params = listView.getLayoutParams();

//            params.height = totalHeight;
            params.height = totalHeight;
            listView.setLayoutParams(params);
        } catch (Exception e) {
            Log.i("test", e.toString());
        }
    }

    /**
     * 监测到TOKEN过期 直接掉到登录页面
     *
     * @param context
     */
   /* public static void jumptologin(Context context) {
        ToastUtils.Show(context, "token过期了，请重新登录");
        SharePrefesUtil.putValue(context, ShareKeyUtil.ISLOGIN, false);
        Intent intent = new Intent(context, LoginActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }*/


   /* *//**
     * 生成二维码
     *
     * @param content
     * @param newsize
     * @return
     * @throws WriterException
     *//*
    public static Bitmap CreateTwoDCode(String content, int newsize) throws WriterException {
        // 生成二维矩阵,编码时指定大小,不要生成了图片以后再进行缩放,这样会模糊导致识别失败
        BitMatrix matrix = null;
        try {
//            matrix = new MultiFormatWriter().encode(content,
//                    BarcodeFormat.QR_CODE, newsize, newsize);//这种方法不支持生成中文二维码
            matrix = new MultiFormatWriter().encode(new String(content.getBytes("UTF-8"), "ISO-8859-1"),
                    BarcodeFormat.QR_CODE, newsize, newsize);
        } catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
            e.printStackTrace();
        }
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        // 二维矩阵转为一维像素数组,也就是一直横着排了
        int[] pixels = new int[width * height];
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                if (matrix.get(x, y)) {
                    pixels[y * width + x] = 0xff000000;//黑色
                } else {
                    pixels[y * width + x] = 0xffffffff;//白色
                }
            }
        }

        Bitmap bitmap = Bitmap.createBitmap(width, height,
                Bitmap.Config.ARGB_8888);
        // 通过像素数组生成bitmap,具体参考api
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
        return bitmap;
    }


    *//**
     * 在二维码中间添加Logo图案
     *//*
    public static Bitmap addLogo(Bitmap src, Bitmap logo) {
        if (src == null) {
            return null;
        }

        if (logo == null) {
            return src;
        }

        //获取图片的宽高
        int srcWidth = src.getWidth();
        int srcHeight = src.getHeight();
        int logoWidth = logo.getWidth();
        int logoHeight = logo.getHeight();

        if (srcWidth == 0 || srcHeight == 0) {
            return null;
        }

        if (logoWidth == 0 || logoHeight == 0) {
            return src;
        }

        //logo大小为二维码整体大小的1/5    -----1/5可能有问题 这里还是1/7吧
        float scaleFactor = srcWidth * 1.0f / 7 / logoWidth;
        Bitmap bitmap = Bitmap.createBitmap(srcWidth, srcHeight, Bitmap.Config.ARGB_8888);
        try {
            Canvas canvas = new Canvas(bitmap);
            canvas.drawBitmap(src, 0, 0, null);
            canvas.scale(scaleFactor, scaleFactor, srcWidth / 2, srcHeight / 2);
            canvas.drawBitmap(logo, (srcWidth - logoWidth) / 2, (srcHeight - logoHeight) / 2, null);

            canvas.save(Canvas.ALL_SAVE_FLAG);
            canvas.restore();
        } catch (Exception e) {
            bitmap = null;
            e.getStackTrace();
        }

        return bitmap;
    }*/

}
